/*
 * @lc app=leetcode.cn id=1282 lang=typescript
 *
 * [1282] 用户分组
 */

// @lc code=start
function groupThePeople(groupSizes: number[]): number[][] {
  const groups = new Map<number, number[]>();
  const n = groupSizes.length;
  // 使用哈希表，key为组的大小，value为组的索引
  for (let i = 0; i < n; i++) {
    const size = groupSizes[i];
    if (!groups.has(size)) {
      groups.set(size, []);
    }
    groups.get(size)!.push(i);
  }

  const ans: number[][] = [];
  // 遍历哈希表，将每个组的索引放入答案中
  for (const [size, group] of groups.entries()) {
    const groupSize = group.length / size;
    for (let i = 0; i < groupSize; i++) {
      const offset = i * size;
      const temp = [];
      for (let j = 0; j < size; j++) {
        const idx: number = offset + j;
        temp.push(group[idx]);
      }
      ans.push(temp);
    }
  }

  return ans;
}
// @lc code=end
